package whisper.service.job;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import whisper.common.support.DatePattern;
import whisper.common.utils.DateUtils;
import whisper.service.coder.Transcoder;
import whisper.service.constants.TaskStatus;
import whisper.service.domain.db.Task;
import whisper.service.service.TaskService;

import java.util.List;

/**
 * Created by JT on 2018/2/24.
 */
@Component
public class TaskJob {

    @Autowired
    private TaskService taskService;

    @Autowired
    private Transcoder  transcoder;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Scheduled(cron = "*/60 * * * * ?")
    public void runTranscoder() {

        logger.info("转码任务检查，检查是否存在可转码任务！时间:{}", DateUtils.getNowFormat(DatePattern.DATE_PATTERN_STANDARD));

        // 检查任务表，获取等待的任务
        List<Task> needTranscodingList = discoverMediaNeedTranscode();

        // 开始进行转码
        for (Task task : needTranscodingList) {
            transcoder.run(task);
        }

    }

    /**
     * 检测需要转码的任务列表
     * @return
     */
    private List<Task> discoverMediaNeedTranscode() {
        return taskService.findTasksByStatus(TaskStatus.WAIT, TaskStatus.RETRY_1,
                                            TaskStatus.RETRY_2, TaskStatus.RETRY_3);
    }

}
